import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { LoginApi, InfoApi ,logoutApi} from "@/api/acl/login";
import { staticRoutes, allAsyncRoutes, anyRoutes } from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import { cloneDeep } from "lodash";
import router from "@/router";

/**
 * 过滤动态路由表，保留拥有访问权限的路由表
 * @param asyncRoutes 动态路由表
 * @param routes 用户路由权限
 * @returns 拥有访问权限的路由表
 */
const filterRoutes = (asyncRoutes: Array<RouteRecordRaw>, routes: string[]) => {
  return asyncRoutes.filter((asyncRoute) => {
    if (routes.includes(asyncRoute.name as string)) {
      if (asyncRoute.children && asyncRoute.children.length) {
        asyncRoute.children = filterRoutes(asyncRoute.children, routes);
      }
      return true;
    } else {
      return false;
    }
  });
};

/**
 * 动态添加路由
 * @param hasPermissionRoutes 拥有访问权限的路由表
 */
const addRoutes=(hasPermissionRoutes:Array<RouteRecordRaw>)=>{
  hasPermissionRoutes.forEach((route)=>router.addRoute(route))
}


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    // 数据初始化从localStorage将数据取出来
    token: getToken() as string,
    name: "",
    avatar: "",
    routes: [],
    buttons: [],
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      const { token } = await LoginApi(username, password);
      setToken(token);
      this.token = token;
    },

    async getInfo() {
      const res = await InfoApi();
      // console.log(res);
      this.name = res.name;
      this.avatar = res.avatar;
      this.routes = res.routes;
      this.buttons = res.buttons;
      //cloneDeep 克隆一份动态子路由表,防止修改了原数据
      const hasPermissionRoutes=filterRoutes(cloneDeep(allAsyncRoutes), res.routes)
    // 将拥有权限访问的路由表，动态添加到路由中生效
      addRoutes([...hasPermissionRoutes,...anyRoutes])
      this.menuRoutes=[...staticRoutes,...hasPermissionRoutes]
    },
    
    async logout() {
      await logoutApi(); // 发送请求，删除服务器的token
      this.reset(); // 删除客户端的用户数据
    },
    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
      this.routes = [];
      this.buttons = [];
    },
  },
});
